import asyncio

from bin.openapi import OpenApiBase

semaphore = asyncio.Semaphore(10)


class BaseApi:
    HOST = "https://openapi.lingxing.com"
    APP_ID = "ak_A77HkbumPXlk3"
    APP_SERCRET = "6z+ZCTX2z5ctgITSuH+akQ=="

    def __init__(self):
        self.op_api = OpenApiBase(BaseApi.HOST, BaseApi.APP_ID, BaseApi.APP_SERCRET)
        self.access_token = ""
        self.refresh_token = ""

    async def generate_access_token(self):
        resp = await self.op_api.generate_access_token()
        self.access_token = resp.access_token
        self.refresh_token = resp.refresh_token
        assert resp.access_token

    async def refresh_access_token(self):
        resp = await self.op_api.refresh_token(self.refresh_token)
        self.refresh_token = resp.refresh_token
        assert resp.access_token

    async def check_token(self, data):
        if data['code'] == 0:
            return True
        elif data['code'] == 2001005:
            await self.refresh_access_token()
            return False
        else:
            print(data['code'])
            return False

    async def main(self):
        await self.generate_access_token()

async def run_api():
    api = BaseApi()
    await api.main()
    return api
